package com.kzw.oa.action.system;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.kzw.core.Constants;
import com.kzw.core.command.QueryFilter;
import com.kzw.core.log.Action;
import com.kzw.core.mapper.Jackson;
import com.kzw.core.model.OnlineUser;
import com.kzw.core.orm.Page;
import com.kzw.core.orm.PageRequest;
import com.kzw.core.orm.StringPropertyFilter;
import com.kzw.core.util.AppUtil;
import com.kzw.core.util.BeanUtil;
import com.kzw.core.util.ContextUtil;
import com.kzw.core.util.ExtjsUtil;
import com.kzw.core.util.JsonUtil;
import com.kzw.core.util.StringUtil;
import com.kzw.core.web.action.BaseAction;
import com.kzw.core.web.paging.PagingBean;
import com.kzw.oa.model.system.AppRole;
import com.kzw.oa.model.system.AppUser;
import com.kzw.oa.model.system.Department;
import com.kzw.oa.model.system.IndexDisplay;
import com.kzw.oa.model.system.PanelItem;
import com.kzw.oa.model.system.SysConfig;
import com.kzw.oa.model.system.UserOrg;
import com.kzw.oa.service.ext.AppUserService2;
import com.kzw.oa.service.ext.DepartmentService2;
import com.kzw.oa.service.system.AppRoleService;
import com.kzw.oa.service.system.AppUserService;
import com.kzw.oa.service.system.DepartmentService;
import com.kzw.oa.service.system.IndexDisplayService;
import com.kzw.oa.service.system.RelativeUserService;
import com.kzw.oa.service.system.SysConfigService;
import com.kzw.oa.service.system.UserOrgService;
import com.kzw.oa.util.JSON;
import com.kzw.oa.util.JSON2;

import flexjson.JSONSerializer;
import flexjson.transformer.DateTransformer;

public class AppUserAction extends BaseAction {
	@Resource
	private DepartmentService2 deptService;
	@Resource
	UserOrgService userOrgService;

	private static Long SUPPER_MANAGER_ID = -1L;// 超级管理员角色ID
	@Resource
	private AppUserService appUserService;
	@Resource
	private DepartmentService departmentService;
	@Resource
	private AppRoleService appRoleService;

	@Resource
	private IndexDisplayService indexDisplayService;

	@Resource
	private SysConfigService sysConfigService;
	@Resource
	private RelativeUserService relativeUserService;
	@Autowired
	private AppUserService2 appUserService2;

	private AppUser appUser;
	private Long userId;
	private Long depId;
	private Long roleId;

	

	/**
	 * 显示当前用户,并且加载该用户的所有权限
	 * 
	 * @return
	 */
	public String getCurrent() {
		AppUser currentUser = ContextUtil.getCurrentUser();
		Department curDep = currentUser.getDepartment();
		if (curDep == null) {// 若所属部门为空，则设置一个缺省的部门 TODO
			curDep = new Department();
			curDep.setDepId(0l);
			curDep.setDepName(AppUtil.getCompanyName());
		}
		// 去掉公共权限
		// Iterator<String> publicIds = AppUtil.getPublicMenuIds().iterator();
		// StringBuffer publicIdSb = new StringBuffer();
		//
		// while (publicIds.hasNext()) {
		// publicIdSb.append(",").append(publicIds.next());
		// }
		List<IndexDisplay> list = indexDisplayService.findByUser(currentUser
				.getUserId());
		List<PanelItem> items = new ArrayList<PanelItem>();
		for (IndexDisplay id : list) {
			PanelItem pi = new PanelItem();
			pi.setPanelId(id.getPortalId());
			pi.setColumn(id.getColNum());
			pi.setRow(id.getRowNum());
			items.add(pi);
		}
		StringBuffer sb = new StringBuffer();
		sb.append("{success:true,user:{userId:'").append(
				currentUser.getUserId()).append("',fullname:'").append(
				currentUser.getFullname()).append("',username:'").append(
				currentUser.getUsername()).append("',depId:'").append(
				curDep.getDepId()).append("',depName:'").append(
				curDep.getDepName()).append("',rights:'");
		sb.append(currentUser.getRights().toString().replace("[", "").replace(
				"]", ""));
		// 去掉公共权限
		// if (!"".equals(currentUser.getRights()) && publicIdSb.length() > 0) {
		// sb.append(publicIdSb.toString());
		// }

		Gson gson = new Gson();
		sb.append("',topModules:");
		sb.append(gson.toJson(currentUser.getTopModules().values()));
		sb.append(",items:").append(gson.toJson(items).toString());
		sb.append("},sysConfigs:{");
		// 系统配置也在此时加载
		List<SysConfig> sysConfigs = sysConfigService.getAll();
		for (SysConfig sysConfig : sysConfigs) {
			sb.append("'").append(sysConfig.getConfigKey()).append("':'")
					.append(sysConfig.getDataValue()).append("',");
		}
		if (sysConfigs.size() > 0) {
			sb.deleteCharAt(sb.length() - 1);
		}
		sb.append("}}");

		setJsonString(sb.toString());
		return SUCCESS;
	}

	/**
	 * 列出所有账号(不列出超级管理员)
	 */
	public String list() {
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(getRequest());
		filters.add(new StringPropertyFilter("EQH_delFlag", Constants.FLAG_UNDELETED+""));
		// 不显示管理员
		filters.add(new StringPropertyFilter("GTL_userId", "1"));
		// 只需要子单位账号
		String path = ContextUtil.getCurrentDept().getPath();
		filters.add(new StringPropertyFilter("STARTLKS_department.path", path));

		PageRequest pageRequest = ExtjsUtil.getPageReq(getRequest());
		if(pageRequest.getOrderBy() == null) {
			pageRequest.setOrderBy("orgSn,userSn,userId");
			pageRequest.setOrderDir("asc,asc,asc");
		}

		Page<AppUser> page = appUserService2.search2(pageRequest, filters);

		jsonString = new JSON(page).buildWithFilters(3, "appUsers", "userOrgs",
				"department", "orgs", "roles", "authorities", "password",
				"positions", "topModules", "rights", "demension", "company");

		return SUCCESS;
	}
	public String list2() {
		QueryFilter filter = new QueryFilter(getRequest());
		filter.addFilter("Q_delFlag_SN_EQ", Constants.FLAG_UNDELETED.toString());
		List<AppUser> list = appUserService.getAll(filter);
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':").append(filter.getPagingBean().getTotalItems()).append(",result:");
		JSONSerializer serializer = new JSONSerializer();
		serializer.transform(new DateTransformer("yyyy-MM-dd"),new String[] { "accessionTime" });
		buff.append(serializer.exclude(new String[] {"password", "demension"}).serialize(list));
		buff.append("}");
		jsonString = buff.toString();
		return SUCCESS;
	}
	/**
	 * 列出某几个账号
	 * by sunziruo
	 */
	public String list3() {
		
		String users = getRequest().getParameter("users");
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(getRequest());
		filters.add(new StringPropertyFilter("INL_userId", users));

		filters.add(new StringPropertyFilter("EQH_delFlag", Constants.FLAG_UNDELETED+""));
		// 不显示管理员
		filters.add(new StringPropertyFilter("GTL_userId", "1"));


		PageRequest pageRequest = ExtjsUtil.getPageReq(getRequest());
		if(pageRequest.getOrderBy() == null) {
			pageRequest.setOrderBy("orgSn,userSn,userId");
			pageRequest.setOrderDir("asc,asc,asc");
		}

		Page<AppUser> page = appUserService2.search2(pageRequest, filters);

		jsonString = new JSON(page).buildWithFilters(3, "appUsers", "userOrgs",
				"department", "orgs", "roles", "authorities", "password",
				"positions", "topModules", "rights", "demension", "company");

		return SUCCESS;
	}

	/**
	 * 根据部门查找列表, 增加条件：用户类型
	 */
	public String select() {
		// 是否根据角色查询翻页
		String roleId = getRequest().getParameter("roleId");
		if (StringUtils.isNotEmpty(roleId)) {
			return find();
		}
		// 是否根据查询条件再翻页查询
		String fullname = getRequest().getParameter("Q_fullname_S_LK");
		if (StringUtils.isNotEmpty(fullname)) {
			return list();	//条件查询
		}
		PagingBean pb = getInitPagingBean();
		String strDepId = getRequest().getParameter("depId");
		// 表示从上级目录开始进行查找
		String path = "0.";
		appUser = ContextUtil.getCurrentUser();
		if (StringUtils.isNotEmpty(strDepId)) {
			Long depId = Long.parseLong(strDepId);
			Department dep = departmentService.get(depId);
			if (dep != null) {
				path = dep.getPath();
			}
		} else {
			Department dep = appUser.getDepartment();
			if (dep != null) {
				path = dep.getPath();
			}
		}

		String _roleType = getRequest().getParameter("roleType");
		Integer roleType = null;
		if(StringUtils.isNotBlank(_roleType) && !"0".equals(_roleType)) {
			roleType = Integer.parseInt(_roleType);
		}
		List<AppUser> list = appUserService.findByDepartment(path, roleType, pb);
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
				.append(pb.getTotalItems()).append(",result:");

		Type type = new TypeToken<List<AppUser>>() {
		}.getType();
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
				.setDateFormat("yyyy-MM-dd").create();

		buff.append(gson.toJson(list, type));
		buff.append("}");

		jsonString = buff.toString();
		return SUCCESS;
	}
	
	/**
	 * 根据部门查找列表
	 */
	public String select2() {		
		PageRequest pageRequest = ExtjsUtil.getPageReq(getRequest());
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(getRequest());
				
		String strDepId = getRequest().getParameter("depId");
		// 表示从上级目录开始进行查找
		String path = "0.";
		appUser = ContextUtil.getCurrentUser();
		if (StringUtils.isNotEmpty(strDepId)) {
			Long depId = Long.parseLong(strDepId);
			Department dep = departmentService.get(depId);
			if (dep != null) {
				path = dep.getPath();
			}
		} else {
			Department dep = appUser.getDepartment();
			if (dep != null) {
				path = dep.getPath();
			}
		}
		filters.add(new StringPropertyFilter("STARTLKS_department.path", path));	
		Page<AppUser> page = appUserService2.search2(pageRequest, filters);
		
		jsonString = new JSON2(page)
				.with(AppUser.class, "userId", "fullname", "title").toJson();
		return SUCCESS;
	}

	/**
	 * 在线用户
	 */
	public String online() {
		Map<String, OnlineUser> onlineUsers = new HashMap<String, OnlineUser>();
		Map<String, OnlineUser> onlineUsersByDep = new HashMap<String, OnlineUser>();
		Map<String, OnlineUser> onlineUsersByRole = new HashMap<String, OnlineUser>();

		onlineUsers = AppUtil.getOnlineUsers();// 获得所有在线用户

		// 按部门选择在线用户
		if (depId != null) {
			for (String sessionId : onlineUsers.keySet()) {
				OnlineUser onlineUser = new OnlineUser();
				onlineUser = onlineUsers.get(sessionId);
				// if(onlineUser.getDepId().equals(depId)){
				String path = "";
				if (!onlineUser.getUserId().equals(AppUser.SUPER_USER)) {
					path = onlineUser.getDepPath();
				}
				// FIXME: 在线用户
				if (!depId.equals(new Long(0))) {
					if (Pattern.compile("." + depId + ".").matcher(path).find()) {
						onlineUsersByDep.put(sessionId, onlineUser);
					}
				} else {
					onlineUsersByDep.put(sessionId, onlineUser);
				}
			}
		}

		// 按角色选择在线用户
		if (roleId != null) {
			for (String sessionId : onlineUsers.keySet()) {
				OnlineUser onlineUser = new OnlineUser();
				onlineUser = onlineUsers.get(sessionId);
				if (Pattern.compile("," + roleId + ",").matcher(onlineUser.getRoleIds()).find()) {
					onlineUsersByRole.put(sessionId, onlineUser);
				}
			}
		}

		Type type = new TypeToken<java.util.Collection<OnlineUser>>() {
		}.getType();
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
				.append(onlineUsers.size()).append(",result:");

		Gson gson = new Gson();
		if (depId != null) {
			buff.append(gson.toJson(onlineUsersByDep.values(), type));
		} else if (roleId != null) {
			buff.append(gson.toJson(onlineUsersByRole.values(), type));
		} else {
			buff.append(gson.toJson(onlineUsers.values(), type));
		}
		buff.append("}");
		jsonString = buff.toString();
		return SUCCESS;
	}

	/**
	 * 根据角色查询
	 */
	public String find() {
		String strRoleId = getRequest().getParameter("roleId");
		PagingBean pb = getInitPagingBean();
		if (StringUtils.isNotEmpty(strRoleId)) {
			List<AppUser> userList = appUserService.findByRole(Long
					.parseLong(strRoleId), pb);
			Type type = new TypeToken<List<AppUser>>() {
			}.getType();
			StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
					.append(pb.getTotalItems()).append(",result:");
			Gson gson = new GsonBuilder()
					.excludeFieldsWithoutExposeAnnotation().create();
			buff.append(gson.toJson(userList, type));
			buff.append("}");

			jsonString = buff.toString();
		} else {
			jsonString = "{success:false}";
		}
		return SUCCESS;
	}

	/**
	 * 批量删除
	 */
	public String multiDel() {

		String[] ids = getRequest().getParameterValues("ids");
		StringBuffer buff = new StringBuffer("{success:true");
		if (ids != null) {
			buff.append(",msg:'");
			for (String id : ids) {
				AppUser delUser = appUserService.get(new Long(id));
				AppRole superManager = appRoleService.get(SUPPER_MANAGER_ID);
				if (delUser.getRoles().contains(superManager)) {
					buff.append("员工:").append(delUser.getUsername()).append(
							"是超级管理员,不能删除!<br><br/>");
				} else if (delUser.getUserId().equals(
						ContextUtil.getCurrentUserId())) {
					buff.append("不能删除自己!<br></br>");
				} else {
					delUser.setStatus(Constants.FLAG_DISABLE);
					delUser.setDelFlag(Constants.FLAG_DELETED);
					
					//FIXME: 删除用户时，还能通过组织机构引用到他？？
					//delUser.setOrgId(null);
					//delUser.setDepartment(null);
					
					delUser.setFullname("[" + delUser.getUsername() + "]");
					delUser.setUsername("__" + delUser.getUsername());
					appUserService.save(delUser);
				}
			}
			buff.append("'");
		}
		buff.append("}");
		setJsonString(buff.toString());
		return SUCCESS;
	}

	/**
	 * 显示详细信息
	 */
	public String get() {
		AppUser appUser = null;
		if (userId != null) {
			appUser = appUserService.get(userId);
		} else {
			appUser = appUserService.get(ContextUtil.getCurrentUserId());
		}
		// 将数据转成JSON格式
		jsonString = new JSON(appUser).buildWithFilters(2, "department",
				"company", "roles", "authorities", "password");
		return SUCCESS;
	}

	/**
	 * 查询已有角色
	 */
	public String selectedRoles() {
		if (userId != null) {
			setAppUser(appUserService.get(userId));
			Set<AppRole> roles = appUser.getRoles();
			StringBuffer sb = new StringBuffer("[");
			for (AppRole role : roles) {
				sb.append("['" + role.getRoleId() + "','" + role.getRoleName()
						+ "'],");
			}
			sb.deleteCharAt(sb.length() - 1);
			sb.append("]");
			setJsonString(sb.toString());
		}
		return SUCCESS;
	}

	/**
	 * 为某一用户提供可选的角色
	 */
	public String getRoles() {

		List<AppRole> list = appRoleService.getAll();
		String userId = getRequest().getParameter("userId");

		List<AppRole> allRole = new ArrayList<AppRole>();

		Set curRoles = new HashSet();
		if (StringUtils.isNotEmpty(userId)) {
			AppUser user = appUserService.get(new Long(userId));
			curRoles = user.getRoles();
		}
		for (AppRole role : list) {
			if (!curRoles.contains(role)
					&& role.getStatus() != Constants.FLAG_DISABLE) {
				allRole.add(role);
			}
		}

		Type type = new TypeToken<List<AppRole>>() {
		}.getType();
		StringBuffer buff = new StringBuffer("{success:true,result:");
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
				.create();
		buff.append(gson.toJson(allRole, type));
		buff.append("}");
		jsonString = buff.toString();

		return SUCCESS;
	}

	/**
	 * 返回某一用户已有的角色
	 * 
	 * @return
	 */
	public String getSelRoles() {
		String userId = getRequest().getParameter("userId");

		if (StringUtils.isNotEmpty(userId)) {
			AppUser user = appUserService.get(new Long(userId));
			Set<AppRole> curRoles = user.getRoles();

			Type type = new TypeToken<Set<AppRole>>() {
			}.getType();
			StringBuffer buff = new StringBuffer("{success:true,result:");
			Gson gson = new GsonBuilder()
					.excludeFieldsWithoutExposeAnnotation().create();
			buff.append(gson.toJson(curRoles, type));
			buff.append("}");
			jsonString = buff.toString();

		}
		return SUCCESS;
	}

	/**
	 * 按职位查找所有用户 信息
	 */
	public String posUsers() {
		String posId = getRequest().getParameter("posId");
		QueryFilter filter = new QueryFilter(getRequest());
		if (StringUtils.isNotEmpty(posId) && !"0".equals(posId)) {
			filter.addFilter("Q_positions.posId_L_EQ", posId.trim());
		}

		filter
				.addFilter("Q_delFlag_SN_EQ", Constants.FLAG_UNDELETED
						.toString());

		List<AppUser> users = appUserService.getAll(filter);

		Type type = new TypeToken<List<AppUser>>() {
		}.getType();
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
				.append(filter.getPagingBean().getTotalItems()).append(
						",result:");
		// Gson gson = new
		// GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
		// buff.append(gson.toJson(users, type));
		JSONSerializer serializer = new JSONSerializer();
		serializer.transform(new DateTransformer("yyyy-MM-dd"),
				new String[] { "accessionTime" });
		buff.append(serializer.exclude(new String[] { "password" }).serialize(
				users));
		buff.append("}");
		jsonString = buff.toString();
		return SUCCESS;
	}

	/**
	 * 查询可选角色
	 */
	public String chooseRoles() {
		List<AppRole> chooseRoles = appRoleService.getAll();
		if (userId != null) {
			setAppUser(appUserService.get(userId));
			Set<AppRole> selectedRoles = appUser.getRoles();
			for (AppRole role : selectedRoles) {
				chooseRoles.remove(role);
			}
		}
		StringBuffer sb = new StringBuffer("[");
		for (AppRole role : chooseRoles) {
			if (role.getStatus() != 0) {
				sb.append("['" + role.getRoleId() + "','" + role.getRoleName()
						+ "'],");
			}
		}
		sb.deleteCharAt(sb.length() - 1);
		sb.append("]");
		setJsonString(sb.toString());
		return SUCCESS;
	}

	/**
	 * 修改密码
	 */
	@Action(description = "修改密码")
	public String resetPassword() {
		String userId = getRequest().getParameter("appUserUserId");
		String oldPassword = StringUtil.encryptSha256(getRequest()
				.getParameter("oldPassword"));
		String newPassword = getRequest().getParameter("newPassword");
		String againPassword = getRequest().getParameter("againPassword");
		if (StringUtils.isNotEmpty(userId)) {
			setAppUser(appUserService.get(new Long(userId)));
		} else {
			setAppUser(ContextUtil.getCurrentUser());
		}
		StringBuffer msg = new StringBuffer("{msg:'");
		boolean pass = false;
		if (oldPassword.equals(appUser.getPassword())) {
			if (newPassword.equals(againPassword)) {
				pass = true;
			} else
				msg.append("两次输入不一致.'");
		} else
			msg.append("旧密码输入不正确.'");
		if (pass) {
			appUser.setPassword(StringUtil.encryptSha256(newPassword));
			appUserService.save(appUser);
			setJsonString("{success:true}");
		} else {
			msg.append(",failure:true}");
			setJsonString(msg.toString());
		}
		return SUCCESS;
	}

	/**
	 * 重置密码
	 */
	@Action(description = "重置密码")
	public String createPassword() {
		String userId = getRequest().getParameter("appUserUserId");
		String newPassword = getRequest().getParameter("newpassword");
		String password = getRequest().getParameter("password");
		StringBuffer msg = new StringBuffer("{msg:'");
		if (StringUtils.isNotEmpty(userId)) {
			setAppUser(appUserService.get(new Long(userId)));
		} else {
			setAppUser(ContextUtil.getCurrentUser());
		}

		if (newPassword.equals(password)) {
			appUser.setPassword(StringUtil.encryptSha256(newPassword));
			appUserService.save(appUser);
			setJsonString("{success:true}");
		} else {
			msg.append("重置失败!,两次输入的密码不一致,请重新输入!.'");
			msg.append(",failure:true}");
			setJsonString(msg.toString());
		}

		return SUCCESS;
	}

	/**
	 * 删除用户照片
	 */
	public String photo() {
		setAppUser(appUserService.get(getUserId()));
		appUser.setPhoto("");
		appUserService.save(appUser);
		return SUCCESS;
	}

	/**
	 * 按部门查找合适做下属的用户
	 */
	public String subAdepartment() {
		PagingBean pb = getInitPagingBean();
		String strDepId = getRequest().getParameter("depId");
		String path = "0.";
		AppUser user = ContextUtil.getCurrentUser();
		if (StringUtils.isNotEmpty(strDepId)) {
			Long depId = Long.parseLong(strDepId);
			Department dep = departmentService.get(depId);
			if (dep != null) {
				path = dep.getPath();
			}
		} else {
			Department dep = user.getDepartment();
			if (dep != null) {
				path = dep.getPath();
			}
		}
		if ("0.".equals(path)) {
			path = null;
		}
		Long uId = user.getUserId();

		// Set<Long> userIds = userSubService.findAllUpUser(uId);
		// List<Long> userIdsL = userSubService.subUsers(uId);

		// userIds.add(uId);
		// for (Long l : userIdsL) {
		// userIds.add(l);
		// }

		List<AppUser> list = appUserService.findSubAppUser(path, new HashSet(),
				pb);
		Type type = new TypeToken<List<AppUser>>() {
		}.getType();
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
				.append(pb.getTotalItems()).append(",result:");
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
				.create();
		buff.append(gson.toJson(list, type));
		buff.append("}");
		jsonString = buff.toString();
		return SUCCESS;
	}

	/**
	 * 根据角色来选择合适做下属的用户
	 */
	public String subArole() {
		String strRoleId = getRequest().getParameter("roleId");
		PagingBean pb = getInitPagingBean();
		AppUser user = ContextUtil.getCurrentUser();
		if (StringUtils.isNotEmpty(strRoleId)) {
			Long uId = user.getUserId();
			// Set<Long> userIds = userSubService.findAllUpUser(uId);
			// List<Long> userIdsL = userSubService.subUsers(uId);
			// userIds.add(uId);
			// for (Long l : userIdsL) {
			// userIds.add(l);
			// }
			// List<AppUser> userList = appUserService.findSubAppUserByRole(
			// new Long(strRoleId), userIds, pb);
			// List<AppUser>
			// userList=appUserService.findByRole(Long.parseLong(strRoleId),
			// pb);
			Type type = new TypeToken<List<AppUser>>() {
			}.getType();
			StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
					.append(pb.getTotalItems()).append(",result:");
			Gson gson = new GsonBuilder()
					.excludeFieldsWithoutExposeAnnotation().create();
			buff.append(gson.toJson(new ArrayList(), type));
			buff.append("}");
			jsonString = buff.toString();
		} else {
			jsonString = "{success:false}";
		}
		return SUCCESS;
	}

	/**
	 * 按在线查找合适当下属的用户
	 */
	public String onlineAsub() {
		Map<String, OnlineUser> onlineUsers = new HashMap<String, OnlineUser>();
		Map<String, OnlineUser> onlineUsersBySub = new HashMap<String, OnlineUser>();
		onlineUsers = AppUtil.getOnlineUsers();// 获得所有在线用户
		// 按在线用户
		AppUser user = ContextUtil.getCurrentUser();
		Long uId = user.getUserId();
		Set<Long> userIds = new HashSet();// userSubService.findAllUpUser(uId);
		userIds.add(uId);
		List<Long> userIdsL = new ArrayList();// userSubService.subUsers(uId);
		for (Long l : userIdsL) {
			userIds.add(l);
		}
		for (String sessionId : onlineUsers.keySet()) {
			OnlineUser onlineUser = new OnlineUser();
			onlineUser = onlineUsers.get(sessionId);
			if (!userIds.contains(onlineUser.getUserId())) {
				onlineUsersBySub.put(sessionId, onlineUser);
			}
		}
		Type type = new TypeToken<java.util.Collection<OnlineUser>>() {
		}.getType();
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
				.append(onlineUsers.size()).append(",result:");
		Gson gson = new Gson();
		buff.append(gson.toJson(onlineUsersBySub.values(), type));
		buff.append("}");
		jsonString = buff.toString();
		return SUCCESS;
	}

	/**
	 * 上属
	 */
	public String upUser() {
		Set<AppUser> set = relativeUserService.getUpUser(ContextUtil
				.getCurrentUserId());

		StringBuffer buff = new StringBuffer("[");
		for (Iterator it = set.iterator(); it.hasNext();) {
			AppUser user = (AppUser) it.next();
			buff.append("['" + user.getUserId().toString() + "','"
					+ user.getFullname() + "'],");
		}
		if (set.size() > 0) {
			buff.deleteCharAt(buff.length() - 1);
		}
		buff.append("]");
		setJsonString(buff.toString());
		return SUCCESS;
	}

	/**
	 * 当前用户修改个人资料
	 */
	@Action(description = "修改个人资料")
	public String profile() {

		AppUser curAppUser = ContextUtil.getCurrentUser();
		AppUser orgAppUser = appUserService.get(curAppUser.getUserId());

		orgAppUser.setFullname(appUser.getFullname());
		orgAppUser.setEmail(appUser.getEmail());
		orgAppUser.setTitle(appUser.getTitle());
		orgAppUser.setPhone(appUser.getPhone());
		orgAppUser.setMobile(appUser.getMobile());
		orgAppUser.setFax(appUser.getFax());
		orgAppUser.setAddress(appUser.getAddress());
		orgAppUser.setZip(appUser.getZip());
		orgAppUser.setPhoto(appUser.getPhoto());

		appUserService.save(orgAppUser);
		// 使其不需要重新登录都能正常显示已经修改过的用户名
		curAppUser.setFullname(orgAppUser.getFullname());

		jsonString = "{success:true}";
		return SUCCESS;
	}

	/**
	 * 针对对话框的用户选择及条件过滤
	 * 按角色查找失败？？
	 */
	public String dialog() {
//		QueryFilter filter = new QueryFilter(getRequest());
//		// 是否为显示当前部门的员工
//		String curDep = getRequest().getParameter("curDep");
//		if (StringUtils.isNotEmpty(curDep)) {
//			AppUser curUser = ContextUtil.getCurrentUser();
//			filter.addFilter("Q_department.depId_L_EQ", curUser.getOrgId().toString());
//		}
//		// 显示非删除的用户
//		filter.addFilter("Q_delFlag_SN_EQ", "0");
//		List<AppUser> userList = appUserService.getAll(filter);
//		
//		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
//				.append(filter.getPagingBean().getTotalItems()).append(
//						",result:");
//		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
//				.create();
//		Type type = new TypeToken<List<AppUser>>() {
//		}.getType();
//		buff.append(gson.toJson(userList, type));
//		buff.append("}");
//		jsonString = buff.toString();
		
		
		//需要排序
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(getRequest());
		String orgId = getRequest().getParameter("orgId");
		if(StringUtils.isNotBlank(orgId)) {
			Department dept = deptService.get(Long.parseLong(orgId));
			filters.add(new StringPropertyFilter("STARTLKS_department.path", dept.getPath()));
		}
		
		// 是否为显示当前部门的员工
		String curDep = getRequest().getParameter("curDep");
		if (StringUtils.isNotEmpty(curDep)) {
			AppUser curUser = ContextUtil.getCurrentUser();
			filters.add(new StringPropertyFilter("EQL_orgId", curUser.getOrgId().toString()));
		}
		// 显示非删除的用户
		filters.add(new StringPropertyFilter("EQH_delFlag", "0"));
		
		PageRequest pageRequest = ExtjsUtil.getPageReq(getRequest());
		pageRequest.setOrderBy("orgSn,userSn");
		pageRequest.setOrderDir("asc,asc");
		Page<AppUser> page = appUserService2.search2(pageRequest, filters);
		
		jsonString = new JSON(page).buildWithFilters(3, "appUsers", "userOrgs",
				"department", "orgs", "roles", "authorities", "password",
				"positions", "topModules", "rights", "demension", "company");
		
		return SUCCESS;
	}

	/**
	 * 保存并更新用户信息
	 */
	public String saveOrUpdate() {		
		if (appUser.getUserId() != null) {
			//修改
			appUser = appUserService.get(appUser.getUserId());
			try {
				BeanUtil.populateEntity(getRequest(), appUser, "appUser");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			//新增
			AppUser au = appUserService.findByUserName(appUser.getUsername());
			if (au != null) {
				jsonString = "{success:false,msg:'该用户已存在'}";
				return SUCCESS;
			}
			appUser.setPassword(StringUtil.encryptSha256(appUser.getPassword()));
			appUser.setDelFlag(Constants.FLAG_UNDELETED);
		}
		appUserService.save(appUser);

		// 处理其对应的部门，用户等
		String roleIds = getRequest().getParameter("roleIds");
		String orgIds = getRequest().getParameter("orgIds");

		if (StringUtils.isNotEmpty(roleIds)) {
			String[] roleIdArr = roleIds.split("[,]");
			// 处理该用户对应的角色
			if (roleIdArr != null) {
				appUser.setRoles(new HashSet<AppRole>());
				for (String roleId : roleIdArr) {
					AppRole role = appRoleService.get(new Long(roleId));
					appUser.getRoles().add(role);
				}
				appUserService.save(appUser);
			}
		}

		Gson gson = new Gson();
		if (StringUtils.isNotEmpty(orgIds)) {
			// 处理orgIds
			UserOrg[] uos = (UserOrg[]) gson.fromJson(orgIds, UserOrg[].class);
			if (uos != null) {
				for (UserOrg uo : uos) {
					uo.setAppUser(appUser);
					Department dept = deptService.get(uo.getOrgId());
					if (uo.getIsPrimary().equals(UserOrg.PRIMARY)) {
						// 设置主部门
						Department dep = departmentService.get(uo.getOrgId());
						appUser.setDepartment(dep);
						// 更新其对应的所属公司ID
						String path = dep.getPath();
						if (path != null) {
							String[] ids = path.split("[.]");
							// 从后向前循环，保存最后的那个公司 (必须有公司类型)
							for (int i = ids.length - 1; i >= 0; i--) {
								String id = ids[i];
								if (!"0".equals(id) && StringUtils.isNotEmpty(id)) {// 不为0
									Department org = (Department) deptService.get(new Long(id));
									// 如果类型为公司，保存相关公司/法院/其它组织信息
									if (Department.ORG_TYPE_COMPANY.equals(org.getOrgType())
											|| Department.ORG_TYPE_GROUP.equals(org.getOrgType())) {
										appUser.setOrgId(new Long(id));
										break;
									}
								}
							}
						}
						appUserService.save(appUser);
					}
					uo.setDept(dept);
					userOrgService.save(uo);
				}
			}
			
			//更新部门的序号
			if(appUser.getOrgId() != null) {
				Department org = deptService.get(appUser.getOrgId());
				appUser.setOrgSn(org.getSn());
				appUserService.save(appUser);
			}
		}
		return SUCCESS;
	}

	/**
	 * 加载表单实体
	 */
	public String load() {
		AppUser appUser = appUserService.get(userId);
		StringBuffer sb = new StringBuffer("{success:true,data:");
		sb.append(new JSON(appUser, true).buildWithFilters(1, "company"));
		sb.append("}");
		jsonString = sb.toString();
		
		return SUCCESS;
	}

	/**
	 * 删除选择择的角色
	 */
	public String delRole() {
		String roleId = getRequest().getParameter("roleId");

		if (StringUtils.isNotEmpty(roleId)) {
			AppUser appUser = appUserService.get(userId);
			AppRole appRole = appRoleService.get(new Long(roleId));
			appUser.getRoles().remove(appRole);
			appUserService.save(appUser);
		}

		return SUCCESS;
	}

	/**
	 * 取得某个部门下的所有用户
	 */
	public String depUsers() {
		String depId = getRequest().getParameter("depId");
		String username = getRequest().getParameter("Q_username_S_LK");
		String fullname = getRequest().getParameter("Q_fullname_S_LK");
		PagingBean pb = getInitPagingBean();
		Department org = null;

		if (StringUtils.isNotEmpty(depId) && !"0".equals(depId)) {
			org = deptService.get(new Long(depId));
		} else {
			org = deptService.get(ContextUtil.getCurrentDept().getDepId());
		}
		String orgPath = (org == null) ? "0." : org.getPath();
		Map<String, String> map = new HashMap<String, String>();
		map.put("username", username == null ? "" : username);
		map.put("fullname", fullname == null ? "" : fullname);
		List<AppUser> users = appUserService.getDepUsers(orgPath, pb, map);

		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
				.append(pb.getTotalItems()).append(",result:[ ");
		Gson gson = new Gson();
		if (users.size() > 0) {
			for (AppUser au : users) {
				if(au.getUserId().equals(AppUser.SUPER_USER)) continue;
				buff.append("{");
				buff.append("\"userId\":").append("\"" + au.getUserId() + "\",");
				buff.append("\"status\":").append("\"" + au.getStatus() + "\",");
				if (au.getUsername() != null) {
					buff.append("\"username\":").append(
							gson.toJson(au.getUsername()) + ",");
				}
				buff.append("\"fullname\":").append(
						gson.toJson(au.getFullname()) + ",");
				if (au.getEmail() != null) {
					buff.append("\"email\":").append(
							gson.toJson(au.getEmail()) + ",");
				}
				if (au.getUserSn() != null) {
					buff.append("\"userSn\":").append(
							gson.toJson(au.getUserSn()) + ",");
				}
				//if (au.getDutyName() != null) {
				//	buff.append("\"dutyName\":").append(
				//			gson.toJson(au.getDutyName()) + ",");
				//}
				if(au.getDutyNames() != null) {
					buff.append("\"dutyNames\":").append(gson.toJson(au.getDutyNames()) + ",");
				}
				buff.append("\"depNames\":").append(
						gson.toJson(au.getDepNames()) + ",");
				buff.append("\"roleNames\":").append(
						gson.toJson(au.getRoleNames()) + ",");
				if(au.getAccessionTime() != null) {
					buff.append("\"accessionTime\":").append(
						gson.toJson(au.getAccessionTime().toString().substring(
								0, 10)));
				} else {
					buff.append("\"accessionTime\": \"\"");
				}
				buff.append("},");
			}
		}
		jsonString = buff.toString().substring(0, buff.length() - 1) + "]}";

		return SUCCESS;
	}

	/**
	 * 关联下拉
	 */
	public String combo() {
		List<AppUser> list = appUserService.findByRoleId(new Long(7));
		StringBuffer sb = new StringBuffer("{success:true").append(",result:");
		JSONSerializer serializer = JsonUtil.getJSONSerializer();
		sb.append(serializer.serialize(list));

		sb.append("}");
		setJsonString(sb.toString());
		return SUCCESS;
	}

	/**
	 * 申请用户
	 */
	public String apply() {
		AppUser user = new AppUser();
		try {
			BeanUtil.populateEntity(getRequest(), user, "appUser");
			AppRole role = appRoleService.getById(new Long(7));
			user.getRoles().add(role);
			user.setDelFlag(new Short("0"));
			user.setTitle(new Short("1"));
			user.setEmail("11@11.com");
			user.setFullname(user.getUsername());
			user.setAccessionTime(new Date());
			user.setPassword(StringUtil.encryptSha256(user.getPassword()));
			user.setStatus(new Short("1"));
			appUserService.save(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// setJsonString("{success:true}");
		return SUCCESS;
	}
	
	/**
	 * 根据部门查找列表
	 * 	找出分管领导（比较特殊） 
	 * 	是否全部显示，还是只显示当前单位	
	 */
	@Deprecated
	public String selectType() {
		HttpServletRequest request = getRequest();
		String roleType = request.getParameter("roleType");
		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		Page<AppUser> page = appUserService2.findByRoleType(pageRequest, Integer.parseInt(roleType));

		jsonString = new JSON2(page).with(AppUser.class, "userId", "fullname", "title").toJson();
		return SUCCESS;
	}

	/**
	 * 选中用户
	 * */
	public String selectedUser() {
		String ids = getRequest().getParameter("ids");
		if(ids.startsWith(",")) {
			ids = ids.substring(1);
		}
		if(ids.endsWith(",")) {
			ids.substring(0, ids.length()-1);
		}
		String hql = "from AppUser where userId in ("+ids+")";
		List<AppUser> users = appUserService2.findByHQL(hql);
		jsonString = Jackson.me().with(AppUser.class, "userId", "fullname").toJson(users);
		return SUCCESS;
	}
	
	/**
	 * 用户类型树
	 * */
	public String treeRole() {
		jsonString = appUserService2.treeUserRole();
		return SUCCESS;
	}
	
	/**
	 * 根据用户类型查找
	 * */
	public String findByRole() {
		HttpServletRequest request = getRequest();
		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		
		String path = ContextUtil.getCurrentDept().getPath();
		filters.add(new StringPropertyFilter("STARTLKS_path", path));
		
		String roleId = request.getParameter("roleId");
		if(!roleId.equals("0")) {
			filters.add(new StringPropertyFilter("EQI_roleType", roleId));
		}
		Page<AppUser> page = appUserService2.search2(pageRequest, filters);
		jsonString = new JSON2(page).with(AppUser.class, "userId", "fullname", "title").toJson();
		return SUCCESS;
	}
	
	/**
	 * 地区下的无人机驾驶员
	 * */
	public String depPlanUser() {
		String depId = getRequest().getParameter("depId");
		HttpServletRequest request = getRequest();
		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		filters.add(new StringPropertyFilter("EQI_roleType", "2"));
		// 本单位或下级单位
		filters.add(new StringPropertyFilter("LIKES_department.path", "."+depId+"."));
		
		Page<AppUser> page = appUserService2.search2(pageRequest, filters);
		jsonString = new JSON2(page).with(AppUser.class, "userId", "userId","fullname",
				"username","cardNo", "status", "depNames", "zhiye").toJson();
		
		System.out.println(jsonString);
		
		return SUCCESS;
	}
	
	/**
	 * 地区下的无人机驾驶员
	 * */
	public String depPlanUser2() {
		HttpServletRequest request = getRequest();
		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		filters.add(new StringPropertyFilter("EQI_roleType", "2"));
		Page<AppUser> page = appUserService2.search2(pageRequest, filters);
		jsonString = new JSON2(page).with(AppUser.class, "userId", "userId","fullname",
				"username","cardNo", "status", "depNames", "zhiye").toJson();
		
		System.out.println(jsonString);
		
		return SUCCESS;
	}
	
	public Long getDepId() {
		return depId;
	}

	public void setDepId(Long depId) {
		this.depId = depId;
	}

	public Long getRoleId() {
		return roleId;
	}

	public void setRoleId(Long roleId) {
		this.roleId = roleId;
	}

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public AppUser getAppUser() {
		return appUser;
	}

	public void setAppUser(AppUser appUser) {
		this.appUser = appUser;
	}
	
}
